package cn.green.components.service;

import cn.green.busi.auth.entity.OAuthUser;
import cn.green.cache.SimpleCache;
import cn.green.components.dao.SysRoleDao;
import cn.green.components.dao.SysUserDao;
import cn.green.components.model.SysRole;
import cn.green.components.model.SysUser;
import cn.green.data.UserDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 实现spring-security提供的UserDetailsService服务组件
 */
@Service
public class DefaultUserDetailService implements UserDetailsService {

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysUserDao sysUserDao;

    //根据用户名查询用户信息功能
    @Override
    public SysUser loadUserByUsername(String s) throws UsernameNotFoundException {
        //这里可以通过数据库来查找到实际的用户信息，这里我们先模拟下,后续我们用数据库来实现
        return UserDataRepository.getSysUser(s);
    }

    public SysUser getUserByNameAndPassword(String username, String password) {
        SysUser param = new SysUser();
        param.setUsername(username);
        param.setPassword(password);
        SysUser byUsernameAndPassword = this.sysUserDao.getByUsernameAndPassword(param);
        if (byUsernameAndPassword != null) {
            String role = byUsernameAndPassword.getRole();
            if (role != null && !"".equals(role)) {
                try {
                    List<SysRole> sysRoleByRoleIds = this.sysRoleDao.getSysRoleByRoleIds(role);
                    byUsernameAndPassword.setAuthority(sysRoleByRoleIds);
                    OAuthUser oAuthUser = new OAuthUser(byUsernameAndPassword);
                    SimpleCache.putOAuth(oAuthUser.getSysUser().getUsername(), oAuthUser);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            }
        }
        return byUsernameAndPassword;
    }
}
